package fr.labri.buganalyzer.writers;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

import fr.labri.buganalyzer.extractors.AbstractExtractor;
import fr.labri.buganalyzer.model.Change;
import fr.labri.buganalyzer.model.Comment;
import fr.labri.buganalyzer.model.Developer;
import fr.labri.buganalyzer.model.Issue;
import fr.labri.buganalyzer.model.Tracker;

public class H2Adapter extends AbstractAdapter {

	public H2Adapter(String dbFile) {
		super(dbFile);
		this.sessionFactory = configureSessionFactory();
		initSession();
	}

	@Override
	protected SessionFactory configureSessionFactory() throws HibernateException {
		Configuration configuration = new Configuration();
		configuration.setProperty("hibernate.connection.url", "jdbc:h2:" + dbFile);
		configuration.configure();
		serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		return sessionFactory;
	}

	@Override
	protected void initSession() {
		sessionFactory = configureSessionFactory();
		session = sessionFactory.openSession();
		session.beginTransaction();
	}

	@Override
	public void save(AbstractExtractor e) {
		
		if(!session.getTransaction().isActive())
			session.beginTransaction();
		
		Tracker tracker = e.getTracker();

		for (Issue bug : e.getIssues()) {
			bug.setTracker(e.getTracker());
			Developer reporter, assignee;
			reporter = bug.getReporter();
			if (reporter != null) {
				reporter.getSubmittedIssues().add(bug);
				reporter.setTracker(tracker);
				tracker.getDevelopers().add(reporter);
			}
			assignee = bug.getAssignee();
			if (assignee != null) {
				assignee.getAssignedIssues().add(bug);
				assignee.setTracker(tracker);
				tracker.getDevelopers().add(assignee);
			}
			for (Comment c : bug.getComments()) {
				Developer s = c.getSubmitter();
				if (s != null)
					s.setTracker(tracker);
			}

			session.save(bug);
		}
		
		for (Change change : e.getChanges()){
			session.save(change);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void loadIssues() {
		if (session != null) {
			List<?> listIssues = session.createQuery("from Issue").list();
			if (listIssues.size() > 0) {
				this.issues.addAll((List<Issue>) listIssues);
			}
		} else
			System.out.println("Session not initilized yet !");
	}

	public void save(Change c) {
		if(!session.getTransaction().isActive())
			session.beginTransaction();
		session.save(c);
	}
}
